﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		BaseEntityPersisterListener.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            BaseEntityPersisterListener.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using NHibernate.Event;
using NHibernate.Persister.Entity;

namespace Dexter.Repository.NHibernate.Listeners {

	internal abstract class BaseEntityPersisterListener : IPreUpdateEventListener , IPreInsertEventListener {
		#region IPreInsertEventListener Members

		/// <summary>
		/// Called when [pre insert].
		/// </summary>
		/// <param name="event">The @event.</param>
		/// <returns></returns>
		public abstract Boolean OnPreInsert ( PreInsertEvent @event );

		#endregion

		#region IPreUpdateEventListener Members

		/// <summary>
		/// Called when [pre update].
		/// </summary>
		/// <param name="event">The @event.</param>
		/// <returns></returns>
		public abstract Boolean OnPreUpdate ( PreUpdateEvent @event );

		#endregion

		protected void Set ( IEntityPersister persister , object[] state , string propertyName , object value ) {
			int index = GetIndexOfProperty ( persister , propertyName );
			state[ index ] = value;
		}

		static int GetIndexOfProperty ( IEntityPersister persister , string propertyName ) {
			int index = Array.IndexOf ( persister.PropertyNames , propertyName );

			if ( index == -1 ) {
				throw new ArgumentException ( string.Format ( "There is no property called {0} in entity {1}" , propertyName , persister.EntityName ) );
			}

			return index;
		}

		protected Object GetState ( IEntityPersister persister , object[] state , string propertyName ) {
			int index = GetIndexOfProperty ( persister , propertyName );
			return state[ index ];
		}

		protected Boolean IsPropertyChanged ( IEntityPersister persister , object[] oldState , object[] state , string propertyName ) {
			return !GetState ( persister , oldState , propertyName )
			        	.Equals ( GetState ( persister , state , propertyName ) );
		}
	}
}
